<template>
  <div class="resume-container">
    <a-card title="智能简历生成" class="resume-card">
      <p class="resume-description">
        填写以下信息，系统将为您智能生成专业简历。<span class="text-required">带*的为必填项</span>
      </p>

      <!-- 简历预览结果 -->
      <div v-if="resumeResult" class="resume-result">
        <a-divider>简历生成结果</a-divider>
        <div class="resume-preview">
          <img :src="resumeResult.previewUrl" alt="简历预览" class="preview-image" />
          <div class="resume-actions">
            <a :href="resumeResult.editUrl" target="_blank" class="edit-link">
              <a-button type="primary"> 编辑简历 </a-button>
            </a>
            <a-button @click="resetForm" style="margin-left: 16px"> 重新生成 </a-button>
          </div>
        </div>
      </div>

      <a-form
        v-show="!resumeResult"
        :model="resumeForm"
        layout="vertical"
        :rules="rules"
        ref="resumeFormRef"
      >
        <!-- 个人信息部分 -->
        <a-collapse v-model:activeKey="activeKeys" class="resume-section">
          <a-collapse-panel key="1" header="个人信息 *">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="姓名" :name="['personalInfo', 'name']">
                  <a-input v-model:value="resumeForm.personalInfo.name" placeholder="请输入姓名" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="年龄" :name="['personalInfo', 'age']">
                  <a-input-number
                    v-model:value="resumeForm.personalInfo.age"
                    :min="16"
                    :max="100"
                    style="width: 100%"
                    placeholder="请输入年龄"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="性别" :name="['personalInfo', 'gender']">
                  <a-radio-group v-model:value="resumeForm.personalInfo.gender">
                    <a-radio :value="0">男</a-radio>
                    <a-radio :value="1">女</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="求职岗位" :name="['personalInfo', 'jobPosition']">
                  <a-input
                    v-model:value="resumeForm.personalInfo.jobPosition"
                    placeholder="请输入求职岗位"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>

        <!-- 教育经历部分 -->
        <a-collapse v-model:activeKey="activeKeys" class="resume-section">
          <a-collapse-panel key="2" header="教育经历 *">
            <div v-for="(edu, index) in resumeForm.education" :key="index" class="edu-item">
              <div class="item-header">
                <h3>教育经历 #{{ index + 1 }}</h3>
                <a-button
                  v-if="resumeForm.education.length > 1"
                  type="text"
                  danger
                  @click="removeEducation(index)"
                >
                  <template #icon><DeleteOutlined /></template>
                  删除
                </a-button>
              </div>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item
                    :label="'学校'"
                    :name="['education', index, 'school']"
                    :rules="[{ required: true, message: '请输入学校名称', trigger: 'blur' }]"
                  >
                    <a-input v-model:value="edu.school" placeholder="请输入学校名称" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item
                    :label="'学历'"
                    :name="['education', index, 'degree']"
                    :rules="[{ required: true, message: '请选择学历', trigger: 'change' }]"
                  >
                    <a-select v-model:value="edu.degree" placeholder="请选择学历">
                      <a-select-option value="高中">高中</a-select-option>
                      <a-select-option value="专科">专科</a-select-option>
                      <a-select-option value="本科">本科</a-select-option>
                      <a-select-option value="硕士">硕士</a-select-option>
                      <a-select-option value="博士">博士</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item
                    :label="'专业'"
                    :name="['education', index, 'major']"
                    :rules="[{ required: true, message: '请输入专业名称', trigger: 'blur' }]"
                  >
                    <a-input v-model:value="edu.major" placeholder="请输入专业名称" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item
                    :label="'时间段'"
                    :name="['education', index, 'timeRange']"
                    :rules="[
                      { required: true, message: '请选择时间段', trigger: 'change', type: 'array' },
                    ]"
                  >
                    <a-range-picker
                      v-model:value="edu.timeRange"
                      style="width: 100%"
                      :placeholder="['开始时间', '结束时间']"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-divider v-if="index < resumeForm.education.length - 1" />
            </div>

            <a-button type="dashed" block @click="addEducation" class="add-btn">
              <PlusOutlined /> 添加教育经历
            </a-button>
          </a-collapse-panel>
        </a-collapse>

        <!-- 实习/工作经历部分 -->
        <a-collapse v-model:activeKey="activeKeys" class="resume-section">
          <a-collapse-panel key="3" header="实习/工作经历">
            <div v-for="(work, index) in resumeForm.workExperience" :key="index" class="work-item">
              <div class="item-header">
                <h3>工作经历 #{{ index + 1 }}</h3>
                <a-button
                  v-if="resumeForm.workExperience.length > 0"
                  type="text"
                  danger
                  @click="removeWorkExperience(index)"
                >
                  <template #icon><DeleteOutlined /></template>
                  删除
                </a-button>
              </div>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item
                    :label="'公司/单位名称'"
                    :name="['workExperience', index, 'company']"
                  >
                    <a-input v-model:value="work.company" placeholder="请输入公司或单位名称" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item :label="'职位'" :name="['workExperience', index, 'position']">
                    <a-input v-model:value="work.position" placeholder="请输入职位名称" />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item :label="'时间段'" :name="['workExperience', index, 'timeRange']">
                    <a-range-picker
                      v-model:value="work.timeRange"
                      style="width: 100%"
                      :placeholder="['开始时间', '结束时间']"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item :label="'工作类型'" :name="['workExperience', index, 'type']">
                    <a-select v-model:value="work.type" placeholder="请选择工作类型">
                      <a-select-option value="实习">实习</a-select-option>
                      <a-select-option value="兼职">兼职</a-select-option>
                      <a-select-option value="全职">全职</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>

              <a-form-item :label="'工作描述'" :name="['workExperience', index, 'description']">
                <a-textarea
                  v-model:value="work.description"
                  placeholder="请描述您的工作职责和成就"
                  :rows="4"
                />
              </a-form-item>

              <a-divider v-if="index < resumeForm.workExperience.length - 1" />
            </div>

            <a-button type="dashed" block @click="addWorkExperience" class="add-btn">
              <PlusOutlined /> 添加工作经历
            </a-button>
          </a-collapse-panel>
        </a-collapse>

        <!-- 校园经历部分 -->
        <a-collapse v-model:activeKey="activeKeys" class="resume-section">
          <a-collapse-panel key="4" header="校园经历">
            <div
              v-for="(campus, index) in resumeForm.campusExperience"
              :key="index"
              class="campus-item"
            >
              <div class="item-header">
                <h3>校园经历 #{{ index + 1 }}</h3>
                <a-button
                  v-if="resumeForm.campusExperience.length > 0"
                  type="text"
                  danger
                  @click="removeCampusExperience(index)"
                >
                  <template #icon><DeleteOutlined /></template>
                  删除
                </a-button>
              </div>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item
                    :label="'组织/活动名称'"
                    :name="['campusExperience', index, 'organization']"
                  >
                    <a-input
                      v-model:value="campus.organization"
                      placeholder="请输入组织或活动名称"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item :label="'职位/角色'" :name="['campusExperience', index, 'role']">
                    <a-input v-model:value="campus.role" placeholder="请输入您的职位或角色" />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item :label="'时间段'" :name="['campusExperience', index, 'timeRange']">
                    <a-range-picker
                      v-model:value="campus.timeRange"
                      style="width: 100%"
                      :placeholder="['开始时间', '结束时间']"
                    />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-form-item :label="'经历描述'" :name="['campusExperience', index, 'description']">
                <a-textarea
                  v-model:value="campus.description"
                  placeholder="请描述您的活动内容和成就"
                  :rows="4"
                />
              </a-form-item>

              <a-divider v-if="index < resumeForm.campusExperience.length - 1" />
            </div>

            <a-button type="dashed" block @click="addCampusExperience" class="add-btn">
              <PlusOutlined /> 添加校园经历
            </a-button>
          </a-collapse-panel>
        </a-collapse>

        <!-- 技能证书部分 -->
        <a-collapse v-model:activeKey="activeKeys" class="resume-section">
          <a-collapse-panel key="5" header="技能证书">
            <div v-for="(cert, index) in resumeForm.certificates" :key="index" class="cert-item">
              <div class="item-header">
                <h3>证书 #{{ index + 1 }}</h3>
                <a-button
                  v-if="resumeForm.certificates.length > 0"
                  type="text"
                  danger
                  @click="removeCertificate(index)"
                >
                  <template #icon><DeleteOutlined /></template>
                  删除
                </a-button>
              </div>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item :label="'证书名称'" :name="['certificates', index, 'name']">
                    <a-input v-model:value="cert.name" placeholder="请输入证书名称" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item :label="'颁发机构'" :name="['certificates', index, 'issuer']">
                    <a-input v-model:value="cert.issuer" placeholder="请输入颁发机构" />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item :label="'获取时间'" :name="['certificates', index, 'date']">
                    <a-date-picker
                      v-model:value="cert.date"
                      style="width: 100%"
                      placeholder="获取时间"
                    />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-divider v-if="index < resumeForm.certificates.length - 1" />
            </div>

            <a-button type="dashed" block @click="addCertificate" class="add-btn">
              <PlusOutlined /> 添加证书
            </a-button>
          </a-collapse-panel>
        </a-collapse>

        <!-- 技能部分 -->
        <a-collapse v-model:activeKey="activeKeys" class="resume-section">
          <a-collapse-panel key="6" header="技能">
            <div v-for="(skill, index) in resumeForm.skills" :key="index" class="skill-item">
              <div class="item-header">
                <h3>技能 #{{ index + 1 }}</h3>
                <a-button
                  v-if="resumeForm.skills.length > 0"
                  type="text"
                  danger
                  @click="removeSkill(index)"
                >
                  <template #icon><DeleteOutlined /></template>
                  删除
                </a-button>
              </div>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item :label="'技能名称'" :name="['skills', index, 'name']">
                    <a-input v-model:value="skill.name" placeholder="请输入技能名称" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item :label="'熟练程度'" :name="['skills', index, 'level']">
                    <a-select v-model:value="skill.level" placeholder="请选择熟练程度">
                      <a-select-option value="入门">入门</a-select-option>
                      <a-select-option value="熟悉">熟悉</a-select-option>
                      <a-select-option value="精通">精通</a-select-option>
                      <a-select-option value="专家">专家</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>

              <a-divider v-if="index < resumeForm.skills.length - 1" />
            </div>

            <a-button type="dashed" block @click="addSkill" class="add-btn">
              <PlusOutlined /> 添加技能
            </a-button>
          </a-collapse-panel>
        </a-collapse>

        <!-- 自我评价部分 -->
        <a-collapse v-model:activeKey="activeKeys" class="resume-section">
          <a-collapse-panel key="7" header="自我评价 *">
            <a-form-item
              :name="'selfEvaluation'"
              :rules="[{ required: true, message: '请填写自我评价', trigger: 'blur' }]"
            >
              <a-textarea
                v-model:value="resumeForm.selfEvaluation"
                placeholder="请简要描述自己的性格特点、职业规划、优势等"
                :rows="6"
              />
            </a-form-item>
          </a-collapse-panel>
        </a-collapse>

        <!-- 提交按钮 -->
        <div class="submit-container">
          <a-button type="primary" size="large" @click="generateResume" :loading="loading">
            智能生成简历
          </a-button>
        </div>
      </a-form>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { generateResumeUsingPost } from '@/api/resumeController'

// 表单引用
const resumeFormRef = ref()
// 加载状态
const loading = ref(false)
// 当前展开的面板
const activeKeys = ref(['1', '2', '7'])
// 简历生成结果
const resumeResult = ref(null)

// 简历表单数据
const resumeForm = reactive({
  // 个人信息
  personalInfo: {
    name: '',
    age: undefined,
    gender: 0,
    jobPosition: '',
  },
  // 教育经历
  education: [
    {
      school: '',
      degree: '',
      major: '',
      timeRange: [],
    },
  ],
  // 工作经历
  workExperience: [],
  // 校园经历
  campusExperience: [],
  // 证书
  certificates: [],
  // 技能
  skills: [],
  // 自我评价
  selfEvaluation: '',
})

// 表单验证规则
const rules = {
  personalInfo: {
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    age: [{ required: true, message: '请输入年龄', trigger: 'change' }],
    jobPosition: [{ required: true, message: '请输入求职岗位', trigger: 'blur' }],
  },
}

// 添加教育经历
const addEducation = () => {
  resumeForm.education.push({
    school: '',
    degree: '',
    major: '',
    timeRange: [],
  })
}

// 删除教育经历
const removeEducation = (index: number) => {
  resumeForm.education.splice(index, 1)
}

// 添加工作经历
const addWorkExperience = () => {
  resumeForm.workExperience.push({
    company: '',
    position: '',
    type: '',
    timeRange: [],
    description: '',
  })
}

// 删除工作经历
const removeWorkExperience = (index: number) => {
  resumeForm.workExperience.splice(index, 1)
}

// 添加校园经历
const addCampusExperience = () => {
  resumeForm.campusExperience.push({
    organization: '',
    role: '',
    timeRange: [],
    description: '',
  })
}

// 删除校园经历
const removeCampusExperience = (index: number) => {
  resumeForm.campusExperience.splice(index, 1)
}

// 添加证书
const addCertificate = () => {
  resumeForm.certificates.push({
    name: '',
    issuer: '',
    date: null,
  })
}

// 删除证书
const removeCertificate = (index: number) => {
  resumeForm.certificates.splice(index, 1)
}

// 添加技能
const addSkill = () => {
  resumeForm.skills.push({
    name: '',
    level: '',
  })
}

// 删除技能
const removeSkill = (index: number) => {
  resumeForm.skills.splice(index, 1)
}

// 重置表单和结果
const resetForm = () => {
  resumeResult.value = null
}

// 生成简历
const generateResume = async () => {
  try {
    // 验证表单
    await resumeFormRef.value.validate()

    loading.value = true

    // 检查是否有教育经历
    if (resumeForm.education.length === 0) {
      message.error('请至少添加一条教育经历')
      loading.value = false
      return
    }

    // 调用接口生成简历
    const data = await generateResumeUsingPost(resumeForm as any)
    if (data.code === 0) {
      message.success('简历生成成功')
      console.log(data.data)

      // 解析返回的数据
      const responseText = data.data

      // 提取预览图片URL和编辑链接
      const previewUrlMatch = responseText.match(/!\[简历图片预览 简历图片\]\((.*?)\)/)
      const editUrlMatch = responseText.match(/\[「编辑简历」\]\((.*?)\)/)

      if (previewUrlMatch && previewUrlMatch[1] && editUrlMatch && editUrlMatch[1]) {
        resumeResult.value = {
          previewUrl: previewUrlMatch[1],
          editUrl: editUrlMatch[1]
        } as any
      } else {
        message.warning('简历已生成，但无法解析预览链接')
      }
    } else {
      message.error('简历生成失败')
    }
    loading.value = false
  } catch (error) {
    loading.value = false
    console.error('表单验证失败:', error)
    message.error('请检查表单填写是否正确')
  }
}
</script>

<style scoped>
.resume-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 24px;
}

.resume-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-radius: 8px;
}

.resume-description {
  margin-bottom: 24px;
  color: #666;
  font-size: 14px;
}

.text-required {
  color: #ff4d4f;
  margin-left: 8px;
}

.resume-section {
  margin-bottom: 16px;
  border-radius: 4px;
  overflow: hidden;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.item-header h3 {
  margin: 0;
  font-size: 16px;
  color: #1890ff;
}

.add-btn {
  margin-top: 16px;
}

.submit-container {
  text-align: center;
  margin: 32px 0 16px;
}

/* 添加简历预览相关样式 */
.resume-result {
  margin-top: 20px;
  text-align: center;
}

.resume-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 20px 0;
}

.preview-image {
  max-width: 100%;
  max-height: 600px;
  border: 1px solid #eee;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.resume-actions {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

.edit-link {
  text-decoration: none;
}
</style>
